package cn.com.cfae.iras.doc.analyze.components.consistency;

import cn.com.cfae.iras.doc.analyze.components.BaseComponent;
import cn.com.cfae.iras.doc.analyze.components.beans.ComponentResult;
import cn.com.cfae.iras.doc.analyze.parse.kv.KVText;
import cn.com.cfae.iras.doc.analyze.parse.kv.TextLayout;
import cn.com.cfae.iras.doc.analyze.parse.model.*;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Created by zouxun on 2018/10/29
 */
@Component("U1010")
@Scope("prototype")
public class U1010 extends BaseComponent {
    private static Logger logger = LoggerFactory.getLogger(U1010.class);

    @Autowired
    U1004 u1004;

    @Override
    public List<ComponentResult> handlerM() {
        logger.info("开始调用U1010组件，处理M表...............");
        String m4CatalogId="M-4";
        String m6CatalogId="M-6";
        String m6ChapterId="M-6-3";
        List<ComponentResult> componentResults = ruleCheck(m4CatalogId,m6CatalogId,m6ChapterId);
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerBM() {
        logger.info("开始调用U1010组件，处理BM表...............");
        String m4CatalogId="BM-4";
        String m6CatalogId="BM-6";
        String m6ChapterId="BM-6-3";
        List<ComponentResult> componentResults = ruleCheck(m4CatalogId,m6CatalogId,m6ChapterId);
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerDM() {
        logger.info("开始调用U1010组件，处理DM表...............");
        String m4CatalogId="DM-4";
        String m6CatalogId="DM-6";
        String m6ChapterId="DM-6-3";
        List<ComponentResult> componentResults = ruleCheck(m4CatalogId,m6CatalogId,m6ChapterId);
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerBDM() {
        logger.info("开始调用U1010组件，处理BDM表...............");
        String m4CatalogId="BDM-4";
        String m6CatalogId="BDM-6";
        String m6ChapterId="BDM-6-3";
        List<ComponentResult> componentResults = ruleCheck(m4CatalogId,m6CatalogId,m6ChapterId);
        return componentResults;
    }

    private List<ComponentResult> ruleCheck(String m4CatalogId,String m6CatalogId,String m6ChapterId){
        List<ComponentResult> componentResults = new ArrayList<>();
        String keyWord="募集资金用于偿还有息债务，筛选".concat(m6ChapterId).concat("有息债务章节进行比对");

        ComponentResult componentResult = u1004.getComponentResult(getCatalogId(),getChapterId(),getRuleTitle(),keyWord,"",true,getRegulationId(),1,null,"03");

//        String[] keywordArray = new String[]{"有息债务","有息债务情况","付息债务"};

        DocumentModel documentModel = super.getExtractData();

        ChapterModel m4ChapterModel = documentModel.getChapterModel(m4CatalogId);

        ChapterModel m6ChapterModel=documentModel.getChapterModel(m6CatalogId);

        try{
            if(m4ChapterModel!=null){
                KVText m4KvTextValue = getKVTextValue(m4CatalogId,"MJZJYT","MJZJYT");
                KVText m4KvTextKey = getKVTextKey(m4CatalogId,"MJZJYT","MJZJYT");

                if(m4KvTextKey!=null){
                    String m4KeyText = m4KvTextKey.getText();

                    if(StringUtils.isNotEmpty(m4KeyText)){
                        logger.info("募集资金类型：{}",m4KeyText);

                        boolean m4Flag=false;

                        MJZJYTType[] mjzjytTypes = MJZJYTType.values();

                        for(MJZJYTType mjzjytType:mjzjytTypes){
                            if(mjzjytType.name().equals(m4KeyText)){
                                m4Flag=true;
                                break;
                            }
                        }

                        ComponentResult m4ComponentResult = u1004.getComponentResult(getCatalogId(),getChapterId(),getRuleTitle(),keyWord,"",false,getRegulationId(),m4ChapterModel.getStartPage(),null,"03");

                        if(m4Flag){
                            m4ComponentResult.setPromptMessage(getCatalogId().concat("募集资金用途存在有息债务相关描述"));

                            if(m4KvTextKey!=null){
                                List<ComponentResult.TextPosition> textPositionList = new ArrayList<>();
                                ComponentResult.TextPosition textPosition = new ComponentResult().new TextPosition();
                                TextLayout textLayout = m4KvTextKey.getTextLayout();
                                if(textLayout!=null){
                                    textPosition.setX(textLayout.getLeft());
                                    textPosition.setY(textLayout.getTop());
                                    textPosition.setContent(textLayout.getText());
                                    logger.info("第四章有息债务描述：{}",textLayout.getText());
                                    m4ComponentResult.setPageNum(textLayout.getPageNumber());
                                    textPositionList.add(textPosition);
                                }
                                m4ComponentResult.setTextPosition(textPositionList);
                            }

                            ComponentResult m6ComponentResult = u1004.getComponentResult(getCatalogId(),getChapterId(),getRuleTitle(),keyWord,"",false,getRegulationId(),1,null,"03");

                            if(m6ChapterModel!=null){
                                List<PageModel> pageModelList = m6ChapterModel.getPageModelList();

                                m6ComponentResult.setPageNum(m6ChapterModel.getStartPage());

                                if(CollectionUtils.isNotEmpty(pageModelList)){
                                    boolean flag=false;

                                    top:for(PageModel pageModel:pageModelList){
                                        JsonArray jsonTextDataArray = pageModel.getJsonTextData()!=null?pageModel.getJsonTextData().getAsJsonArray():null;
                                        if(jsonTextDataArray!=null){
                                            for(JsonElement element : jsonTextDataArray){
                                                JsonArray dataArray = element.getAsJsonObject()!=null?element.getAsJsonObject().getAsJsonArray("data"):null;//当页文本
                                                if(dataArray!=null){
                                                    for (int i = 0; i < dataArray.size(); i++) {
                                                        JsonArray e = dataArray.get(i).getAsJsonArray();
                                                        for(int y=0;y<e.size();y++){
                                                            JsonObject data = e.get(y).getAsJsonObject();
                                                            String text = data.get("text").getAsJsonPrimitive().getAsString();
                                                            String top = data.get("top").getAsJsonPrimitive().getAsString();
                                                            String left = data.get("left").getAsJsonPrimitive().getAsString();
                                                            if(text.contains("有息债务情况") || text.contains("发行人有息债务") || text.contains("有息债务分析") || text.contains("付息债务")){
                                                                logger.info("{}第{}行数据，内容：{}。",m6ChapterId, i, text);
                                                                m6ComponentResult.setPageNum(pageModel.getPageNumber());
                                                                m6ComponentResult.setPromptMessage(m6ChapterId.concat("存在有息债务相关描述，请人工核对"));
                                                                List<ComponentResult.TextPosition> textPositionList = new ArrayList<>();
                                                                ComponentResult.TextPosition textPosition = new ComponentResult().new TextPosition();
                                                                textPosition.setX(Double.valueOf(left));
                                                                textPosition.setY(Double.valueOf(top));
                                                                textPosition.setContent(text);
                                                                textPositionList.add(textPosition);
                                                                m6ComponentResult.setTextPosition(textPositionList);
                                                                flag=true;
                                                                break top;
                                                            }
                                                        }
                                                    }

                                                }
                                            }
                                        }
                                    }

                                    if(!flag){
                                        m6ComponentResult.setPromptMessage(m6ChapterId.concat("中未找到有息债务相关描述，建议人工核对"));
                                        m6ComponentResult.setAnnotationFlag(true);
                                    }

                                }else{
                                    m6ComponentResult.setPromptMessage("未识别".concat(m6ChapterId).concat("数据，建议人工核对"));
                                    if(m6ChapterModel!=null) m6ComponentResult.setPageNum(m6ChapterModel.getStartPage());
                                    m6ComponentResult.setAnnotationFlag(true);
                                }

                            }else {
                                m6ComponentResult.setPromptMessage("未识别".concat(m6ChapterId).concat("数据，建议人工核对"));
                                m6ComponentResult.setAnnotationFlag(true);
                            }

                            componentResults.add(m4ComponentResult);
                            componentResults.add(m6ComponentResult);
                            return componentResults;
                        }else{
                            m4ComponentResult.setPromptMessage(m4CatalogId.concat("募集资金用途无有息债务相关描述"));
                            m4ComponentResult.setExist("01");
                            componentResults.add(m4ComponentResult);
                            return componentResults;
                        }

                    }else{
                        componentResult.setPromptMessage("未识别".concat(m4CatalogId).concat("数据，建议人工核对"));
                        if(m4ChapterModel!=null) componentResult.setPageNum(m4ChapterModel.getStartPage());
                        componentResults.add(componentResult);
                        return componentResults;
                    }
                }else{
                    componentResult.setPromptMessage("未识别".concat(m4CatalogId).concat("数据，建议人工核对"));
                    if(m4ChapterModel!=null) componentResult.setPageNum(m4ChapterModel.getStartPage());
                    componentResults.add(componentResult);
                    return componentResults;
                }
            }else{
                componentResult.setPromptMessage("未识别".concat(m4CatalogId).concat("数据，建议人工核对"));
                componentResults.add(componentResult);
                return componentResults;
            }

        }catch (Exception e){
            logger.error(e.getMessage(),e);
            if(componentResults.size()==0){
                componentResult.setPromptMessage("未识别".concat(m4CatalogId).concat("数据，建议人工核对"));
                if(m4ChapterModel!=null) componentResult.setPageNum(m4ChapterModel.getStartPage());
                componentResults.add(componentResult);
            }
        }

        return componentResults;
    }
}
